//
//  PPWebGrabViewController.m
//  pickpic
//
//  Created by Jinxiao on 9/3/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPWebGrabViewController.h"
#import "PPWebGrabImagesViewController.h"
#import "PPAlbumPictureInsertionViewController.h"

#import "PPAlbumContentViewDataSource.h"

#import "PPWebGrabProtocol.h"

@import WebKit;

@interface PPWebGrabViewController () <WKUIDelegate, WKNavigationDelegate, UITextFieldDelegate, UIWebViewDelegate, PPWebGrabProtocolDelegate>
@property (readwrite, nonatomic, strong) UIWebView *webView;
@property (readwrite, nonatomic, strong) UIButton *button;
@property (readwrite, nonatomic, strong) UILabel *promptLabel;
@property (readwrite, nonatomic, strong) UITextField *URLField;
@property (readwrite, nonatomic, assign) dispatch_once_t once;

@property (readwrite, nonatomic, strong) NSMutableArray *dataSources;
@end

@implementation PPWebGrabViewController

- (void)dealloc {
    if(self.isViewLoaded) {
        [PPWebGrabProtocol unregisterObserver:self];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _dataSources = [[NSMutableArray alloc] init];

    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;

    _URLField = [[UITextField alloc] init];
    _URLField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入网址" attributes:@{NSForegroundColorAttributeName : [UIColor colorWithRGBHex:0xb2b2b2], NSFontAttributeName : [UIFont systemFontOfSize:14]}];
    _URLField.backgroundColor = [UIColor whiteColor];
    _URLField.layer.cornerRadius = 5;
    _URLField.layer.masksToBounds = YES;
    _URLField.frame = CGRectMake(0, 0, self.view.width - 92, 28);
    _URLField.font = [UIFont systemFontOfSize:14];
    _URLField.textColor = [UIColor colorWithRGBHex:0x323232];
    _URLField.delegate = self;
    _URLField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _URLField.autocorrectionType = UITextAutocorrectionTypeNo;
    _URLField.keyboardType = UIKeyboardTypeURL;
    _URLField.returnKeyType = UIReturnKeyDone;
    self.navigationItem.titleView = _URLField;

    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
    leftView.backgroundColor = [UIColor clearColor];
    _URLField.leftView = leftView;
    _URLField.leftViewMode = UITextFieldViewModeAlways;

    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
    rightView.backgroundColor = [UIColor clearColor];
    _URLField.rightView = rightView;
    _URLField.rightViewMode = UITextFieldViewModeAlways;

    _promptLabel = [[UILabel alloc] init];
    _promptLabel.textColor = [UIColor colorWithRGBHex:0xb2b2b2];
    _promptLabel.font = [UIFont systemFontOfSize:14];
    _promptLabel.text = @"请在输入框输入网址";
    [self.view addSubview:_promptLabel];

    [_promptLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(175);
    }];

    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    _button.backgroundColor = [UIColor colorWithRGBHex:0x1a1a1a];
    _button.titleLabel.font = [UIFont systemFontOfSize:17];
    [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_button setTitle:@"抓取" forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(buttonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_button];

    _webView = [[UIWebView alloc] init];
    _webView.delegate = self;
    _webView.hidden = YES;
    [self.view addSubview:_webView];

    __weak typeof(self) weakSelf = self;
    [self setNavigationRightImage:[UIImage imageNamed:@"search-off"] action:^{
        [weakSelf.URLField resignFirstResponder];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];

    [PPWebGrabProtocol registerObserver:self];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    dispatch_once(&_once, ^{
        [_URLField becomeFirstResponder];
    });
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    _button.frame = CGRectMake(0, self.view.height - 49, self.view.width, 49);

    _webView.frame = CGRectMake(0, 0, self.view.width, self.view.height - 49);
}

- (void)backItemDidPressed {
    if([_webView canGoBack]) {
        [_webView goBack];
    } else {
        [_URLField resignFirstResponder];

        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)reloadContent {
    NSString *URLString = _URLField.text;

    if(URLString.length > 0) {

        NSRange range = [URLString rangeOfString:@"http" options:(NSAnchoredSearch|NSCaseInsensitiveSearch)];

        if(range.location == NSNotFound) {
            URLString = [@"http://" stringByAppendingString:URLString];
        }

        NSURL *URL = [NSURL URLWithString:URLString];

        if(URL != nil) {
            [_webView loadRequest:[NSURLRequest requestWithURL:URL]];
        }
    }
}

- (void)refreshButtonDidPressed {
    [self reloadContent];
}

- (void)buttonDidPressed {
    [MobClick event:@"57"];

    PPWebGrabImagesViewController *imageViewController = [[PPWebGrabImagesViewController alloc] init];
    imageViewController.URLStrings = _dataSources;
    [self.navigationController pushViewController:imageViewController animated:YES];
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {

    NSString *URLString = _URLField.text;

    if(URLString.length > 0) {
        UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
        refreshButton.contentEdgeInsets = UIEdgeInsetsMake(4, 4, 4, 4);
        [refreshButton setImage:[UIImage imageNamed:@"data"] forState:UIControlStateNormal];
        [refreshButton sizeToFit];
        [refreshButton addTarget:self action:@selector(refreshButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
        _URLField.rightView = refreshButton;
        _URLField.rightViewMode = UITextFieldViewModeAlways;
    } else {
        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
        rightView.backgroundColor = [UIColor clearColor];
        _URLField.rightView = rightView;
        _URLField.rightViewMode = UITextFieldViewModeAlways;
    }

    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];

        [self reloadContent];

        return NO;
    }

    return YES;
}

#pragma mark - WKWebView

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    [_dataSources removeAllObjects];

    _URLField.text = request.URL.absoluteString;

    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    webView.hidden = NO;
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    if(error != nil) {
        _promptLabel.text = @"您输入的网址不存在";

        webView.hidden = YES;
    }
}

#pragma PPWebGrabProtocolDelegate

- (void)protocol:(PPWebGrabProtocol *)protocal didRecognizedImageURL:(NSURL *)imageURL {
    NSString *src = imageURL.absoluteString;

    if([src hasPrefix:@"data:image/"]) {
        //        src = [src componentsSeparatedByString:@","].lastObject;
        //        NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:src options:kNilOptions];
        //        UIImage *image = [UIImage imageWithData:decodedData];
        //        [_dataSources addSafeObject:image];
    } else {
        [_dataSources addSafeObject:src];
    }
}
@end
